//
//  VideoBrowserViewController.swift
//  MyVideo
//
//  Created by han on 2021/4/20.
//

import UIKit

class VideoBrowserViewController: UICollectionViewController {
    var wantsFullScreen = false
    var playbackController: VideoPlaybackController!
}

extension VideoBrowserViewController {
    override func numberOfSections(in collectionView: UICollectionView) -> Int { 1 }
    
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { playbackController.videos.count }
    
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: VideoBrowserCell.reuseIdentifier, for: indexPath) as! VideoBrowserCell
        let video = playbackController.videos[indexPath.row]
        cell.showVideoButton.isHidden = !wantsFullScreen
        cell.titleLabel.text = video.title
        cell.delegate = self
        return cell
    }
    override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        guard let cell = cell as? VideoBrowserCell else { return }
        if wantsFullScreen {
            playbackController.embed(debugHudForIndexPath: indexPath, in: cell)
        } else {
            playbackController.embed(contentForIndexPath: indexPath, in: self, containerView: cell.videoContainerView)
        }
    }
    
    
    override func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        guard let cell = cell as? VideoBrowserCell else { return }
        cell.playerViewControllerCoordinator = nil
    }
}

extension VideoBrowserViewController: VideoBrowserCellDelegate {
    func videoBrowserCellTapped(_ cell: VideoBrowserCell) {
        // 全屏显示的时候会调用
        if let indexPath = collectionView.indexPath(for: cell) {
            playbackController.present(contentForIndexPath: indexPath, from: self)
        }
    }
}
